package com.pallass.admin.controller;

import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.pallass.admin.domain.SysRole;
import com.pallass.admin.domain.SysUser;
import com.pallass.admin.service.SysRoleService;
import com.pallass.admin.service.SysUserService;
import com.pallass.common.controller.BaseController;
import com.pallass.common.jpa.criteria.OperatorType;
import com.pallass.common.jpa.domain.ListSpecificationBuilder;
import com.pallass.utils.PallassConstants;
import com.pallass.utils.RequestResult;

/**
 * 用户
 * 
 * @author Houor
 *
 * @createTime: 2017-02-27 09:30
 */
@Controller
@RequestMapping("/admin/user")
public class UserController extends BaseController {

	private static Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private SysUserService userService;

	@Autowired
	private SysRoleService roleService;

	@RequestMapping(value = "/index")
	public String index(Model model) {
		model.addAttribute("purl", "admin/user");
		return "admin/user";
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public Page<SysUser> list() {

		ListSpecificationBuilder<SysUser> builder = new ListSpecificationBuilder<>();
		String userName = request.getParameter("userName");
		if (StringUtils.isNotBlank(userName)) {
			builder.add("userName", OperatorType.LIKE, userName);
		}

		return userService.findAll(builder.generateListSpecification(), getPageRequest());
	}

	@RequestMapping(value = "/save")
	@ResponseBody
	public RequestResult save(@RequestBody SysUser user) {
		if (StringUtils.isBlank(user.getUserName())) {
			return RequestResult.failure("用户名称不能为空");
		}
		if (StringUtils.isBlank(user.getEmail())) {
			return RequestResult.failure("用户Email不能为空");
		}

		// 初始化用户密码
		user.setPassword(PallassConstants.INITIAL_PASSWORD);
		if (user.getDepartment() == null || user.getDepartment().getId() == 0) {
			user.setDepartment(null);
		}
		userService.save(user);
		logger.debug("添加用户成功");
		return RequestResult.success("添加用户成功");
	}

	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	@ResponseBody
	public SysUser edit(@PathVariable Integer id) {
		return userService.findOne(id);
	}

	@RequestMapping(value = "/update")
	@ResponseBody
	public RequestResult update(@RequestBody SysUser user) {
		if (StringUtils.isBlank(user.getUserName())) {
			return RequestResult.failure("用户名称不能为空");
		}
		if (StringUtils.isBlank(user.getEmail())) {
			return RequestResult.failure("用户Email不能为空");
		}
		if (user.getDepartment() == null || user.getDepartment().getId() == 0) {
			user.setDepartment(null);
		}
		userService.update(user);
		return RequestResult.success("修改用户成功");
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public RequestResult delete(@RequestBody Integer ids[]) {
		userService.deleteByIdArray(ids);
		return RequestResult.success("删除用户成功");
	}

	@RequestMapping(value = "/grant/{id}", method = RequestMethod.GET)
	@ResponseBody
	public List<SysRole> grant(@PathVariable Integer id) {

		List<SysRole> roleList = roleService.findAll();
		Set<SysRole> roleSet = userService.findOne(id).getRoles();
		if (roleSet != null && !roleSet.isEmpty()) {
			for (SysRole r : roleSet) {
				if (roleSet.contains(r)) {
					r.setChecked(true);
				}
			}
		}

		for (SysRole role : roleList) {
			role.setResources(null);
		}
		return roleList;
	}

	@RequestMapping(value = "/grant/{id}", method = RequestMethod.POST)
	@ResponseBody
	public RequestResult grant(@PathVariable Integer id, @RequestBody(required = false) Integer[] roleIds) {
		userService.grant(id, roleIds);
		return RequestResult.success("角色分配成功");
	}
	
	@RequestMapping(value = "/resetpw/{id}", method = RequestMethod.POST)
	@ResponseBody
	public RequestResult resetpw(@PathVariable Integer id) {
		userService.resetpw(id);
		return RequestResult.success("用户密码重置成功");
	}

}
